package com.jichaoyun.controller;

import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.dao.mapper.RealdataCacheMapper;
import com.jichaoyun.model.entity.RealdataCache;
import com.jichaoyun.model.vo.DayDataVo;
import com.jichaoyun.service.IFlowHourService;
import com.jichaoyun.service.IRealdataCacheService;
import com.jichaoyun.service.IRealdataService;
import com.jichaoyun.service.IStationInfoService;
import com.jichaoyun.service.util.TcpUtils.TcpConnect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"查询数据接口"})
@RequestMapping("/sys/DataQuery")
public class DataQueryController {

    @Autowired
    private IStationInfoService stationInfoService;

    @Autowired
    private IFlowHourService flowHourService;

    @Autowired
    private IRealdataCacheService realdataCacheService;

    @Autowired
    private IRealdataService realdataService;

    @ApiOperation(value = "查询数据，历史数据，查询某站点选定日期和时分秒的数据",notes = "时间格式 yyyy-MM-dd HH:mm:ss")
    @GetMapping("/getHourDataByTime")
    public Result<Map<String,Object>> getHourDataByTime(String stationName,String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime datetime = LocalDateTime.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getDataByTime(stationName,datetime));
    }

    @ApiOperation("查询数据，流量分析，分析选定日期的单个站点的流速数据")
    @GetMapping("/analyzeFlowByDate")
    public Result<Map<String,Object>> analyzeFlowByDate(String stationName,String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getFlowByDateTime(stationName,datetime));
    }

    @ApiOperation("查询数据，温度分析，分析选定日期的单个站点的温度数据")
    @GetMapping("/analyzeTempByDate")
    public Result<Map<String,Object>> analyzeTempByDate(String stationName,String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getTempByDateTime(stationName,datetime));
    }

    @ApiOperation("查询数据，压力分析，分析选定日期的单个站点的压力数据")
    @GetMapping("/analyzePresByDate")
    public Result<Map<String,Object>> analyzePresByDate(String stationName,String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getPresByDateTime(stationName,datetime));
    }

    @ApiOperation("查询数据，流量分析，分析所有站点选定日期的流速数据")
    @GetMapping("/analyzeAllFlowByDate")
    public Result<PagedResult> analyzeAllFlowByDate(String date, Integer pageNo) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getAllFlowByDate(datetime,pageNo,8));
    }

    @ApiOperation(value = "查询数据，流量分析，流量分析表，导出到Excel")
    @GetMapping("/DownloadAnalyzeFlow")
    public void DownloadAnalyzeFlow(String localDate, HttpServletResponse response) throws IOException {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(localDate,dateTimeFormatter);

        flowHourService.getAllFlowAnalyzeExcel(datetime,response);
    }

    @ApiOperation("查询数据，温度分析，分析所有站点选定日期的温度数据")
    @GetMapping("/analyzeAllTempByDate")
    public Result<PagedResult> analyzeAllTempByDate(String date, Integer pageNo) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getAllTempByDate(datetime,pageNo,8));
    }

    @ApiOperation(value = "查询数据，温度分析，温度分析表，导出到Excel")
    @GetMapping("/DownloadAnalyzeTemp")
    public void DownloadAnalyzeTemp(String localDate, HttpServletResponse response) throws IOException {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(localDate,dateTimeFormatter);

        flowHourService.getAllTempAnalyzeExcel(datetime,response);
    }

    @ApiOperation("查询数据，压力分析，分析所有站点选定日期的压力数据")
    @GetMapping("/analyzeAllPresByDate")
    public Result<PagedResult> analyzeAllPresByDate(String date, Integer pageNo) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(flowHourService.getAllPresByDate(datetime,pageNo,8));
    }

    @ApiOperation(value = "查询数据，压力分析，压力分析表，导出到Excel")
    @GetMapping("/DownloadAnalyzePres")
    public void DownloadAnalyzePres(String localDate, HttpServletResponse response) throws IOException {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate datetime = LocalDate.parse(localDate,dateTimeFormatter);

        flowHourService.getAllPresAnalyzeExcel(datetime,response);
    }

    @ApiOperation("查询数据，30分钟曲线，查询近30分钟数据")
    @GetMapping("/getHalfHourRealData")
    public Result<Map<String,List<Object>>> getHalfHourRealData(String stationName) {
        return Result.success(realdataCacheService.getHalfHourRealData(stationName));
    }

    @ApiOperation("查询数据，任意区间的曲线")
    @GetMapping("/getAnyPeriodRealData")
    public Result<Map<String,Object>> getAnyPeriodRealData(Integer stationNo,String start ,String end) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime s1  = LocalDateTime.parse(start,dateTimeFormatter);
        LocalDateTime e1  = LocalDateTime.parse(end,dateTimeFormatter);
        return Result.success(realdataService.getAnyPeriodRealData(stationNo,s1,e1));
    }


    @ApiOperation("查询数据，当日流量排名，查询选定日期和时间的当日流量排名")
    @GetMapping("/getFlowRankListByDate")
    public Result<Map<String,Float>> getFlowRankListByDate(String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(stationInfoService.getFlowRankListByDate(datetime));
    }

    @ApiOperation("查询数据，当日温度排名，查询选定日期和时间的当日温度排名")
    @GetMapping("/getTempRankListByDate")
    public Result<Map<String,Float>> getTempRankListByDate(String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(stationInfoService.getTempRankListByDate(datetime));
    }

    @ApiOperation("查询数据，当日压力排名，查询选定日期和时间的当日压力排名")
    @GetMapping("/getPresRankListByDate")
    public Result<Map<String,Float>> getPresRankListByDate(String date) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        return Result.success(stationInfoService.getPresRankListByDate(datetime));
    }

    @Autowired
    private RealdataCacheMapper realdataCacheMapper;
    @ApiOperation("（根据站号）大屏查询某个站点的实时数据")
    @GetMapping("/getRealDataByStation")
    public Result<Map<String,Object>> getRealDataByStation(Integer stationNo) {
        Map<String,Object> res = new LinkedHashMap<>();
        RealdataCache realdataCache = realdataCacheMapper.selectRecentOneByStation(stationNo);
        if(realdataCache==null){
            res.put("流量",null);
            res.put("温度",null);
            res.put("压力",null);
            res.put("密度",null);
            res.put("电压",null);
            res.put("供电",null);
            res.put("通讯","通讯中断");
            res.put("柜门",null);
            res.put("总量",null);
            return Result.success(res);
        }else{
            res.put("流量",realdataCache.getFlow());
            res.put("温度",realdataCache.getTemp());
            res.put("压力",realdataCache.getPres());
            res.put("密度",realdataCache.getDensity());
            res.put("电压",realdataCache.getVoltage());
            res.put("供电", realdataCache.getIsDc() ? "直流": "交流");
            res.put("通讯",TcpConnect.clientInfoMap.containsKey(stationNo) ? "通讯正常":"通讯中断");
            res.put("柜门",realdataCache.getDoorOpen() ? "门开":"门关" );
            res.put("总量",realdataCache.getTotal());
        }
        return Result.success(res);
    }

    @ApiOperation("查询数据，分析三日后趋势")
    @GetMapping("/getFutureData")
    public Result<Map<Integer, DayDataVo>> getFutureData(Integer stationNo,String date){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        // 1. 获取那天的 00:00:00
        LocalDateTime todayStart = datetime.atStartOfDay(); // 2024-03-15 00:00:00

        // 2. 计算前3天的起始时间（大前天的 00:00:00）
        LocalDateTime threeDaysAgoStart = todayStart.minusDays(3); // 2024-03-12 00:00:00

        return Result.success(stationInfoService.getFutureData(stationNo,todayStart,threeDaysAgoStart));
    }

    @ApiOperation("导出“三日后趋势“数据到excel表")
    @GetMapping("/getFutureData2Excel")
    public void getFutureData2Excel(Integer stationNo,String date, HttpServletResponse response){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        LocalDate datetime = LocalDate.parse(date,dateTimeFormatter);

        // 1. 获取那天的 00:00:00
        LocalDateTime todayStart = datetime.atStartOfDay(); // 2024-03-15 00:00:00

        // 2. 计算前3天的起始时间（大前天的 00:00:00）
        LocalDateTime threeDaysAgoStart = todayStart.minusDays(3); // 2024-03-12 00:00:00

        stationInfoService.getFutureData2Excel(stationNo,todayStart,threeDaysAgoStart,response);
    }
}
